package com.allwees.bs.c.common.aop;

import com.allwees.bs.c.module.product.dao.SkuDao;
import com.allwees.bs.c.module.product.dto.ProductDetailsDTO;
import com.allwees.bs.c.module.product.dto.SkuDTO;
import com.allwees.bs.c.module.product.entity.SkuEntity;
import com.allwees.bs.core.model.product.entity.SkuModel;
import com.allwees.bs.core.modelbase.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author Daniel
 * @Version 1.0.0
 * @Description
 * @CreateTime 2020/10/14 15:58
 */
@Component
@Aspect
@Slf4j
public class FetchInventoryAspect {

    @Resource
    private SkuDao skuDao;

    @Pointcut("@annotation(com.allwees.bs.core.model.product.annotation.FetchInventory)")
    public void pointcut() {}

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object result = pjp.proceed();
        if (result instanceof R) {
            R r = (R) result;
            process(r.get("data"));
        }
        return result;
    }

    private void process(Object obj) {
        if (obj instanceof ProductDetailsDTO) {
            ProductDetailsDTO dto = (ProductDetailsDTO) obj;
            log.info("aspect process ProductDetailsDTO:{}", dto);
            if (dto.getSkus() != null && dto.getSkus().getSkus() != null) {
                Map<String, SkuDTO> skuMap = dto.getSkus().getSkus().stream().collect(Collectors.toMap(SkuModel::getUuid, e -> e));
                List<SkuEntity> skus = skuDao.fetchQuantity(new ArrayList<>(skuMap.keySet()));
                for (SkuEntity sku : skus) {
                    int quantity = sku.getQuantity();
                    quantity = Math.max(quantity, 0);
                    skuMap.get(sku.getUuid()).setQuantity(quantity);
                }
            }
        }
    }
}
